#coding:utf8
import re
horizonal_split_rules = {"plan_oneday_h":{"mod_value":20, "keyword":"plan_id"}, "plan_onedayevent_h":{"mod_value":50, "keyword":"plan_id"}, "plan_onedayevent_traffic_h":{"mod_value":50, "keyword":"plan_id"}, "attachments_h":{"mod_value":100, "keyword":"tid"}, "favorites_h":{"mod_value":100, "keyword":"tid"}, "posts_h":{"keyword":"tid", "mod_value":100}, "member_h":{"mod_value":100, "keyword":"uid"}}

#处理sql中反斜杠\以及引号问题
def sql_transform(s) :
    s = s.replace("\\", "\\\\")
    s = s.replace("'", "\\'")
    return s

#数据库分表sql改写
def horizonal_sql(sql, data = None) :
    tablename_match = re.search("from[ ]+(\S+)", sql)
    if not tablename_match : return sql
    table_name = tablename_match.group(1)
    temp = table_name.split(".")
    if len(temp) > 1 : table = temp[1]
    else : table = table_name
    if table not in horizonal_split_rules : return sql
    split_rule = horizonal_split_rules[table]
    mod_value = split_rule["mod_value"]
    keyword = split_rule["keyword"]
    if mod_value == 0 : return sql
    if data : query_sql = sql % tuple(map(str, data))
    else : query_sql = sql

    keyword_match = re.search("%s[ ]+=[ ]+(\d+)"%keyword, query_sql)
    if keyword_match :
        xid = keyword_match.group(1)
        table_index = int(xid) % mod_value
        sql = sql.replace(table_name, "%s_%d" % (table_name, table_index))
        return sql
    else :
        keywords_match = re.search(r"%s[ ]+in[ ]+\(([\d ,]*)\)"%keyword, query_sql)
        if not keywords_match : return sql
        sql_lists = []
        tableindex_xids_dict = {}
        xids = keywords_match.group(1).split(",")
        for xid in xids :
            xid = xid.strip()
            table_index = int(xid) % mod_value
            if table_index not in tableindex_xids_dict : tableindex_xids_dict[table_index] = [xid]
            else : tableindex_xids_dict[table_index].append(xid)
        for tableindex, xids in tableindex_xids_dict.iteritems() :
            new_sql = sql.replace(table_name, "%s_%d" % (table_name, tableindex)).replace(keywords_match.group(0), "%s in (%s)" % (keyword, ",".join(xids)))
            sql_lists.append("(%s)" % new_sql)
        if len(sql_lists) : return " union ".join(sql_lists)
        else : return sql

